package com.ruhua.java.api;

import com.ruhua.java.core.LocalUser;
import com.ruhua.java.core.interceptors.ScopeLevel;
import com.ruhua.java.dto.TokenDTO;
import com.ruhua.java.dto.TokenGetDTO;
import com.ruhua.java.exception.NotFoundException;
import com.ruhua.java.exception.TrowException;
import com.ruhua.java.service.WxAuthenticationService;
import com.ruhua.java.util.JwtToken;
import com.ruhua.java.vo.ResVO;
import com.ruhua.java.vo.UserVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
public class TokenController {

    @Autowired
    private WxAuthenticationService wxAuthenticationService;


    @PostMapping("token")
    public Map<String, String> getToken(@RequestBody @Validated TokenGetDTO userData) {
        System.out.println("x1");
        Map<String, String> map = new HashMap<>();
        String token = null;
        switch (userData.getType()) {
            case USER_WX:
                System.out.println(11);
                token = wxAuthenticationService.code2Session(userData.getAccount());
                break;
            case USER_Email:
                System.out.println(22);
                break;
            default:
                System.out.println(33);
                throw new NotFoundException(10001);
        }
        map.put("token", token);
        return map;
    }


    @PostMapping("weixin/get_xcx_token")
    public ResVO<Map> wxToken(@RequestBody  Map<String,String> person) {
        String code = person.get("code");
        if (code == null || code.length()<6) {
            throw new TrowException("code错误");
        }
        String token = wxAuthenticationService.code2Session(code);
        Map<String, String> map = new HashMap<>();
        map.put("token", token);
        return ResVO.go(map);
    }


    @PostMapping("/verify")
    public Map<String, Boolean> verify(@RequestBody TokenDTO token) {
        Map<String, Boolean> map = new HashMap<>();
        Boolean valid = JwtToken.verifyToken(token.getToken());
        map.put("is_valid", valid);
        return map;
    }


    @GetMapping("index/verify_token")
    @ScopeLevel()
    public ResVO<String> user_verify_token() {
        Long uid = LocalUser.getUser().getId(); if(uid == null){
           throw new TrowException("token已失效");
        }
        return ResVO.go();
    }
}
